import React from 'react';
import { Modal, message, Tabs, Empty } from 'antd';
import cass from 'classnames';
import s from './index.module.less';
import projectServer from '../../services/project';
import taskServer from '../../services/task';
import SearchInput from '../SearchInput';
import TaskItem from '../TaskItem';
import isSuccess from '../../utils/error';
import CustomModal from './CustomModal';

const { forUploadTaskList: getTaskList } = taskServer;
const { linkProjectList: getProjectList, getFolderlist } = projectServer;

const TabPane = Tabs.TabPane;
const typeConfig = {
    '1': { label: '民' },
    '2': { label: '刑' },
    '3': { label: '法' },
    '4': { label: '专' },
}

class PickerModal extends React.Component {

    static defaultProps = {
        needReflesh: 'false', // 用于项目模块添加自定义文件夹后刷新文件夹列表
    }

    constructor(props) {
        super(props);
        this.state = {
            type: props.type,
            projectList: [],
            taskList: [],
            folderlist: [],
            leftActiveIndex: '',
            rightActiveIndex: ''
        }
    }

    componentWillMount() {
        const { hiddenTask } = this.props;
        // 请求所有项目和任务列表
        this.getProjectList();
        if (!hiddenTask) this.getTaskList();
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.needReflesh !== nextProps.needReflesh) {
            this.getProjectList();
        }
    }

    getProjectList = async (params) => {
        const res = await getProjectList(params);
        if (isSuccess(res) && res.data) {
            // 初始化默认数据
            const { type, projectid, projecttype, stageid } = this.props;
            if (!params && type === '1' && projectid && res.data.length) {
                const pi = res.data.findIndex(v => v.recid === projectid);
                if (pi >= 0) {
                    const si = res.data[pi].stages.findIndex(v => v.stageid === stageid);
                    if (si >= 0) {
                        this.getFolderlist({ projectid, projecttype, stageid });
                    }
                    this.setState({ leftActiveIndex: `${pi}-${si}` });
                }
            }
            this.setState({ projectList: res.data || [] });
        }
    }

    getTaskList = async (params) => {
        const res = await getTaskList(params);
        if (isSuccess(res) && res.data) {
            // 初始化默认数据
            const { type, taskid } = this.props;
            if (!params && type === '2' && taskid && res.data.length) {
                const ti = res.data.findIndex(v => v.recid === taskid);
                this.setState({ leftActiveIndex: ti < 0 ? 0 : ti });
            }
            this.setState({ taskList: res.data || [] });
        }
    }

    getFolderlist = async (params) => {
        const res = await getFolderlist(params);
        if (isSuccess(res)) {
            // console.log('---UploadModal getFolderlist---', res);
            this.setState({ folderlist: res.data || [] });
        }
    }

    handleCancel = () => {

        this.setState({ type: this.props.type, rightActiveIndex: '' });
        // 恢复默认
        const { hiddenTask } = this.props;
        this.getProjectList();
        if (!hiddenTask) this.getTaskList();
        this.props.onCancel();
    }

    handleOk = () => {
        const { leftActiveIndex, rightActiveIndex, type } = this.state;
        if (type === '1' && !rightActiveIndex && rightActiveIndex !== 0) {
            message.warn('请选择文件夹');
            return;
        }
        if (type === '2' && !leftActiveIndex && leftActiveIndex !== 0 && leftActiveIndex !== '-') {
            message.warn('请选择任务');
            return;
        }
        let returnObj = {};
        if (type === '1') {
            const [pathValue, p, s, f] = this.getPathValue(type);
            returnObj = { project: p, stage: s, folder: f, pathValue, type };
        } else if (type === '2') {
            const [pathValue, t] = this.getPathValue(type);
            returnObj = { task: t, pathValue, type };
        }

        this.props.onOk(returnObj, this.handleCancel);
    }

    getPathValue = (type) => {
        const { hiddenTask } = this.props;
        const { projectList, taskList, folderlist, leftActiveIndex, rightActiveIndex } = this.state;
        let value = [''];

        if (
            (!leftActiveIndex && leftActiveIndex !== 0) ||
            (type === '1' && !projectList.length) ||
            (type === '2' && !hiddenTask && !taskList.length)
        ) return value;

        if (type === '1' && (typeof leftActiveIndex === 'string')) {
            const [pi, si] = leftActiveIndex.split('-');
            const p = projectList[pi];
            const s = projectList[pi].stages[si];
            // 项目名称-阶段名称-文件夹名称
            const pathValue = `[${s.stagename}] ${p.recname}`;
            value = [pathValue, p, s];
            if ((rightActiveIndex || rightActiveIndex === 0) && folderlist.length) {
                const f = folderlist[rightActiveIndex];
                value[0] = `${f.foldername}-${value[0]}`;
                value.push(f);
            }
        } else if (type === '2' && (typeof leftActiveIndex === 'number')) {
            // 任务名称
            const t = taskList[leftActiveIndex];
            if (t) {
                const pathValue = t.content;
                value = [pathValue, t]
            }
        }
        return value;
    }

    onTabsChange = (key) => {
        this.setState({ type: key });
    }

    onSearch = (v, type) => {
        if (type === '1') {
            this.getProjectList({ searchkey: v });
        } else if (type === '2') {
            this.getTaskList({ searchkey: v });
        };
        this.setState({ folderlist: [], leftActiveIndex: '' });
    }

    selectProject = (v, i) => {
        const idxs = i.split('-');
        this.getFolderlist({
            projectid: v.recid,
            projecttype: v.projecttype,
            stageid: v.stages[idxs[1]].stageid
        })
        this.setState({ leftActiveIndex: i, rightActiveIndex: '' });
    }

    selectTask = (v, i) => {
        this.setState({ leftActiveIndex: i, rightActiveIndex: '' });
    }

    renderItem = (type, list) => {
        const { leftActiveIndex } = this.state;
        if (!list.length) {
            return (
                <div className={s.empty}>
                    <Empty
                        description={type === '1' ? '暂无项目' : '暂无任务'}
                    />
                </div>
            )
        }
        if (type === '1') {
            return list.map((v, i) => (
                <div
                    key={v.recid}
                    className={s.wrapItem}
                >
                    <div className={s.top}>
                        <div>{typeConfig[v.projecttype].label}</div>
                        <h3>{v.recname}</h3>
                    </div>
                    <div className={cass(s.bottom)}>
                        {v.stages.map((d, idx) => (
                            <div
                                key={idx}
                                onClick={() => this.selectProject(v, `${i}-${idx}`)}
                                className={cass('hovergray', { [s.active]: leftActiveIndex === `${i}-${idx}` })}
                            >
                                {`[${d.stagename}] 委托人：${d.clients.join(';')}`}
                                {d.host ? <span className={cass('mdi', 'mdi-flag')} key="flag" /> : null}
                            </div>
                        ))}
                    </div>
                </div>
            ))
        } else {
            return list.map((v, i) => (
                <TaskItem
                    // unHoverable={true}
                    className={s.taskWrap}
                    key={`taskItem${i}`}
                    data={v}
                    active={leftActiveIndex === i}
                    onClick={() => this.selectTask(v, i)}
                />
            ))
        }
    }

    onSelectFolder = (f, i) => {
        this.setState({ rightActiveIndex: i });
    }

    refleshFolder = ({ selProjectid, selProjecttype, selStageid }) => {
        this.getFolderlist({
            projectid: selProjectid,
            projecttype: selProjecttype,
            stageid: selStageid
        });
    }

    getProductId = (type, leftActiveIndex, projectList) => {
        const returnData = {};
        if (type === '1' && leftActiveIndex && projectList.length && leftActiveIndex.split) {
            const [i, idx] = leftActiveIndex.split('-');
            returnData.selProjectid = projectList[i].recid;
            returnData.selProjecttype = projectList[i].projecttype;
            returnData.selStageid = projectList[i].stages[idx].stageid;
            returnData.inlawyermember = projectList[i].stages[idx].inlawyermember;
        }
        return returnData;
    }

    render() {
        const { visible, title, hiddenTask, showfooter } = this.props;
        const { type, projectList, taskList, folderlist, rightActiveIndex, leftActiveIndex, customModal } = this.state;

        const tabs = [
            { label: '项目', list: projectList, key: '1' },
        ];

        if (!hiddenTask) tabs.push({ label: '任务', list: taskList, key: '2' });

        const pathValue = showfooter ? this.getPathValue(type)[0] : null;
        const idData = this.getProductId(type, leftActiveIndex, projectList);
        const { selProjectid, selStageid, inlawyermember } = idData;
        return (
            <Modal
                title={title}
                width={700}
                okText="确定"
                cancelText="取消"
                visible={visible}
                maskClosable={false}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                wrapClassName={s.wrapInnerModal}
            >
                <div className={s.innerWrap}>
                    <div className={s.left}>
                        <Tabs activeKey={type} onChange={this.onTabsChange}>
                            {tabs.map(d => (
                                <TabPane tab={d.label} key={d.key}>
                                    <div>
                                        <div className={s.search}>
                                            <SearchInput
                                                key={!visible ? Math.random() : 'search'}
                                                placeholder="搜索"
                                                onPressEnter={(v) => this.onSearch(v, type)}
                                                onClear={() => this.onSearch('', type)}
                                            />
                                        </div>
                                        <div className={s.listContent}>
                                            {this.renderItem(d.key, d.list)}
                                        </div>
                                    </div>
                                </TabPane>
                            ))}
                        </Tabs>
                    </div>
                    {type === '1' ? (
                        <div className={s.right}>
                            <div className={s.rightTitle}>
                                选择文件夹
                                <CustomModal
                                    projectid={selProjectid}
                                    stageid={selStageid}
                                    show={customModal}
                                    onSuccess={() => this.refleshFolder(idData)}
                                    onCancel={() => this.setState({ customModal: false })}
                                />
                            </div>
                            {
                                folderlist.length ? (
                                    <div className={s.rightWrap}>
                                        {folderlist.map((v, i) => (
                                            <div
                                                key={v.folderid}
                                                className={cass(s.item, 'hovergray')}
                                                onClick={() => this.onSelectFolder(v, i)}
                                            >
                                                {!v.lawyerfolder ? <span className={cass('mdi mdi-account', s.client)} /> : null}
                                                {v.foldername}
                                                <div className={s.logo}>
                                                    {
                                                        i === rightActiveIndex ?
                                                            <span className="mdi mdi-checkbox-marked-circle" /> :
                                                            <span className="mdi mdi-checkbox-blank-circle-outline" />
                                                    }
                                                </div>
                                            </div>
                                        ))}
                                        {inlawyermember ? (
                                            <div
                                                className={cass(s.item, s.newItem, 'hovergray')}
                                                onClick={() => this.setState({ customModal: true })}
                                            >
                                                <span className={cass('mdi mdi-plus', s.plus)} />
                                            新建文件夹
                                            </div>
                                        ) : null}
                                    </div>
                                ) :
                                    <div className={s.empty}><Empty description={`该项目暂无文件夹，请先自定义文件夹`} /></div>
                            }
                        </div>
                    ) : null}
                    {type === '2' ? (
                        <div className={s.right}>
                            <div className={s.rightTitle}>选择文件夹</div>
                            <div className={s.empty}>
                                <Empty description={'上传任务不需要选择文件夹，请直接确认'} />
                            </div>
                        </div>
                    ) : null}
                    {
                        pathValue ? (
                            <div className={s.footer}>保存路径：{pathValue}</div>
                        ) : null
                    }
                </div>
            </Modal>
        );
    }
}

export default PickerModal